const { Op } = require('sequelize')
const Category = require('../model/categoryModel')
const Article = require('../model/articleModel')

exports.index = async (req, res) => {
  // const categorys = await Category.findAll()

  // const categorys = await Category.findAll({
  //   // include: Article,
  //   include: [{ model: Article }],
  // })

  const categorys = await Category.findByPk(1, {
    include: Article,
  })

  res.json(categorys)
}

exports.add = async (req, res) => {
  let { cate_name } = req.body
  const data = await Category.create({
    cate_name: cate_name,
  })
  res.json(data)
}

exports.update = async (req, res) => {
  let { cate_name, cate_id } = req.body
  const data = Category.update(
    {
      cate_name: cate_name,
    },
    { where: { cate_id: cate_id } }
  )
  res.json(data)
}

exports.delete = async (req, res) => {
  let { cate_id } = req.body
  const data = Category.destroy({ where: { cate_id: cate_id } })
  res.json(data)
}

exports.search = async (req, res) => {
  let { cate_name } = req.query
  const data = await Category.findAll({
    where: {
      cate_name: {
        [Op.like]: `%${cate_name}%`,
      },
    },
  })
  res.json(data)
}
